package com.situ.supermarket.controller;



import com.situ.supermarket.service.UserService;
import com.situ.supermarket.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/login.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserService service = new UserServiceImpl();
        boolean b = service.check(username,password);
        if(b){
            req.getSession().setAttribute("currentUser",username);
            resp.sendRedirect("/index");
        }else {
            req.setAttribute("errorMsg","用户名或密码错误");
            req.getRequestDispatcher("/WEB-INF/login.jsp").forward(req,resp);
        }
    }
    public void logout(HttpServletRequest request,HttpServletResponse response) throws Exception{
        request.getSession().removeAttribute("currentUser");
        response.sendRedirect("/login");
    }
}
